#!/bin/sh
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

[ "$CCI_SRC" ] || export CCI_SRC=$(git rev-parse --show-toplevel)

. $CCI_SRC/lib/log.sh

check_server_ip()
{
	mkdir -p /etc/compass-ci
	cp -a $CCI_SRC/sparrow/setup.yaml /etc/compass-ci/setup.yaml
	[ -z "$server_ip" ] && . 0-package/read-config
	[ -z "$server_ip" ] && {
		log_error "ENV \$server_ip doesn't exist, please config $CCI_SRC/sparrow/setup.yaml"
		exit 1
	}
}

install_env()
{
	cd $CCI_SRC/sparrow || return
	check_server_ip
	0-package/install
	1-storage/tiny
	5-build/ipxe &
	1-storage/permission
	2-network/br0
	2-network/br1
	2-network/iptables
	3-code/git
	3-code/dev-env
	7-systemd/iBMA-install
	. /etc/profile.d/compass.sh
}

boot_ipxe()
{
	SCHED_HOST=$server_ip
	sed -i "s%172.17.0.1%${SCHED_HOST}%g" /tftpboot/boot.ipxe
	sed -i "s%3000%${SCHED_PORT:-3000}%g" /tftpboot/boot.ipxe
}

run_service()
{
	(
		cd $CCI_SRC/container/dnsmasq || return

		local dnsmasq_image_name=dnsmasq:alpine
		local build_dnsmasq_retry=0

		while [[ $build_dnsmasq_retry -lt 3 ]]
		do
			./build
			
			if test "$(docker images -q $dnsmasq_image_name 2> /dev/null)" == ''
			then
				build_dnsmasq_retry=$(($build_dnsmasq_retry + 1))

				continue
			else
				break
			fi
		done

		./start
		boot_ipxe
	)&

	(
		cd $CCI_SRC/container/qemu-efi || return

		local qemu_efi_image_name=debian:qemu-efi
		local build_qemu_efi_retry=0

		while [[ $build_qemu_efi_retry -lt 3 ]]
		do
			./build
			
			if test "$(docker images -q $qemu_efi_image_name 2> /dev/null)" == ''
			then
				build_qemu_efi_retry=$(($build_qemu_efi_retry + 1))
				continue
			else
				break
			fi
		done

		./install
	)&

	(
		cd $CCI_SRC/container/fluentd-base || return

		local fluentd_base_image_name=fluentd-base:alpine
		local build_fluentd_base_retry=0

		while [[ $build_fluentd_base_retry -lt 3 ]]
		do
			./build 

			if test "$(docker images -q $fluentd_base_image_name 2> /dev/null)" == ''
			then
				build_fluentd_base_retry=$(($build_fluentd_base_retry + 1))
				continue
			else
				break
			fi
		done

		cd $CCI_SRC/container/sub-fluentd || return

		./build
		./start
	)&
}

check_service()
{
	for service in dnsmasq sub-fluentd
	do
		docker ps | grep -q $service || {
			log_error "failed to start container $service"
			exit 1
		}
	done

	docker images | grep -q qemu-efi || {
		log_error "failed to build container qemu-efi"
		exit 1
	}
}

check_cmd()
{
	[ -n "$(command -v lockfile-create)" ] || {
		log_error "command not found: lockfile-create"
		exit 1
	}
}

main()
{
	install_env
	run_service
	wait
	check_service
	check_cmd
}

main
